package com.roin.learn.springsecurity.config.security;

import cn.hutool.core.collection.CollUtil;
import com.roin.learn.springsecurity.model.AdminDetails;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Iterator;

/**
 * 动态权限决策管理器，用于判断用户是否有访问权限
 */
public class DynamicAccessDecisionManager implements AccessDecisionManager {
    /**
     * 超级管理员，拥有所有权限
     */
    private final static String SUPER_ADMIN="roinlym";

    @Override
    public void decide(Authentication authentication, Object object,
                       Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

        /**
         * 这里硬编码了超级管理员账号，数据库中也要有这个账号，这个账号拥有所有权限，所在这里直接放行
         */
        AdminDetails adminDetails = (AdminDetails) authentication.getPrincipal();
        if (SUPER_ADMIN.equals(adminDetails.getUsername())) {
            return;
        }

        /**
         * 当接口未被配置资源时直接放行
         * 这里被放行的前提是用户已经成功登录
         */
        if (CollUtil.isEmpty(configAttributes)) {
            return;
        }
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();
        while (iterator.hasNext()) {
            ConfigAttribute configAttribute = iterator.next();
            /**
             * 将访问所需资源或用户拥有资源进行比对
             * 访问资源所需要的权限是在DynamicSecurityMetadataSource中获取的
             * 用户所拥有的权限是在UserDetailsService#loadUserByUsername中设置的
             */
            String needAuthority = configAttribute.getAttribute();
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (needAuthority.trim().equals(grantedAuthority.getAuthority())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("抱歉，您没有访问权限");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}